package com.hwtx.form.plugin;

import com.hwtx.form.annotation.*;
import com.hwtx.form.domain.handle.FormDataHandle;
import com.hwtx.form.domain.repo.SysUserRepo;
import com.hwtx.form.util.FormUtil;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.system.dto.SysUserResetPasswordDto;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Map;

@FormType(value = "userHandle", comment = "用户处理相关")
@Slf4j
public class UserDataHandle implements FormDataHandle {

    public static final String PWD = "pwd";
    public static final String SALT = "salt";
    @Resource
    private SysUserRepo sysUserRepo;

    @Action(
            inputs = {
                    @Parameter(name = PWD, comment = "密码")
            },
            outputs = {
                    @Parameter(name = PWD, comment = "密码"),
                    @Parameter(name = SALT, comment = "盐值")
            })
    @Log(type = OperationType.GET, value = "获取加盐后的密码及盐值")
    public Map<String, String> pwd(Map<String, Object> formData) {
        String pwd = FormUtil.getStrPostValue(formData, PWD);
        if (pwd == null) {
            throw new BusinessException("密码不能为空");
        }
        Pair<String, String> pair = sysUserRepo.genPwd(pwd);
        return Map.of(PWD, pair.getLeft(), SALT, pair.getRight());
    }

    @Action(
            inputs = {
                    @Parameter(name = PWD, comment = "新密码")
            },
            outputs = {
                    @Parameter(name = "ret", comment = "操作是否成功", type = Boolean.class)
            })
    @Log(type = OperationType.GET, value = "重置密码")
    public boolean restPwd(Map<String, Object> formData) {
        Long id = FormUtil.getLongPostValue(formData, "id");
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }
        String newPwd = FormUtil.getStrPostValue(formData, PWD);
        if (newPwd == null) {
            throw new BusinessException("新密码不能为空");
        }
        if (newPwd.length() < 6) {
            throw new BusinessException("新密码长度不能小于6位");
        }
        SysUserResetPasswordDto sysUserResetPasswordDto = new SysUserResetPasswordDto();
        sysUserResetPasswordDto.setIds(id.toString());
        sysUserResetPasswordDto.setPassword(newPwd);
        return sysUserRepo.resetSysUserPassword(sysUserResetPasswordDto);
    }
}